package com.spzx.payment.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.config.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Autowired
    private RabbitService rabbitService;



    //1,后端根据订单信息构造支付宝支付请求参数，
    //2, 并通过 alipayClient.pageExecute 方法将请求发送给支付宝。
    //3,支付宝返回支付表单 HTML，后端将其返回给前端，前端展示支付页面。
    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("/submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable(value = "orderNo") String orderNo) {
        String form = alipayService.submitAlipay(orderNo);
        return success(form);
    }

    //支付宝异步回调
    @SneakyThrows
    @RequestMapping("/callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap) {

        String outTrandNo = paramMap.get("out_trade_no");
        log.info("AlipayController...alipayNotify方法执行了..." + outTrandNo);

        //验签

        //1.去掉sign和sign_type参数
        //2. 将签名参数（sign）使用 base64 解码为字节码串；
        //3. 使用 RSA 的验签方法，通过签名字符串、签名参数（经过base64解码）及支付宝公钥验证签名。
        boolean signVerifed = AlipaySignature.rsaCheckV1(paramMap,
                AlipayConfig.alipay_public_key,
                AlipayConfig.charset,
                AlipayConfig.sign_type);

        if (!signVerifed) {
            log.error("验签失败..." + outTrandNo);
            return  "failure";
        }
        log.info("验签成功..." + outTrandNo);

        //订单状态的判断
        String tradeStatus = paramMap.get("trade_status");
        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {

            //幂等性判断
            PaymentInfo paymentInfo = paymentInfoService.getOne(
                    new LambdaQueryWrapper<PaymentInfo>()
                            .eq(PaymentInfo::getOrderNo, outTrandNo)
                            .eq(PaymentInfo::getPayType, 2)
            );


            if(paymentInfo == null && paymentInfo.getPaymentStatus() == 1){
                return "success";
            }

            // 更新交易记录状态
            paymentInfoService.updatePaymentStatus(paymentInfo, paramMap);


            //订单状态的修改
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PAYMENT_PAY,
                    MqConst.ROUTING_PAYMENT_PAY,
                    outTrandNo);

            //库存的扣减
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_MINUS,
                    outTrandNo);
        }





        return "success" ;
    }


}